<template>
  <div class="history-container">
    <h1 class="page-title">历史任务记录</h1>

    <div class="filters">
      <el-input
        v-model="searchQuery"
        placeholder="搜索任务名称"
        prefix-icon="el-icon-search"
        clearable
        class="search-input"
      />

      <el-select v-model="statusFilter" placeholder="状态" clearable class="filter-select">
        <el-option label="进行中" value="active" />
        <el-option label="已完成" value="completed" />
        <el-option label="已归档" value="archived" />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        class="date-range"
      />

      <el-button type="primary" @click="applyFilters">
        <el-icon><Search /></el-icon>
        应用筛选
      </el-button>
    </div>

    <div class="task-list" v-loading="loading">
      <div v-if="filteredTasks.length === 0" class="empty-state">
        <el-empty description="暂无符合条件的历史任务" />
      </div>

      <el-timeline v-else>
        <el-timeline-item
          v-for="task in filteredTasks"
          :key="task.id"
          :timestamp="task.createTime"
          :type="getTimelineItemType(task.status)"
          :color="getTimelineItemColor(task.status)"
        >
          <el-card class="task-card">
            <template #header>
              <div class="task-header">
                <h3 class="task-title">{{ task.title }}</h3>
                <div class="task-status">
                  <el-tag :type="getStatusTagType(task.status)" size="small">
                    {{ getStatusText(task.status) }}
                  </el-tag>
                </div>
              </div>
            </template>

            <div class="task-content">
              <div class="task-info">
                <div class="info-item">
                  <span class="info-label">课程:</span>
                  <span>{{ task.course }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">班级:</span>
                  <span>{{ task.class }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">完成时间:</span>
                  <span>{{ task.completionTime || '进行中' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">学生参与:</span>
                  <span>{{ task.studentsCount }}人</span>
                </div>
              </div>

              <div class="task-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ task.progressRate }}%</div>
                  <div class="stat-label">完成率</div>
                  <el-progress
                    :percentage="task.progressRate"
                    :status="getProgressStatus(task.progressRate)"
                    :stroke-width="6"
                  />
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ task.avgScore }}</div>
                  <div class="stat-label">平均分</div>
                  <el-progress
                    :percentage="task.avgScore"
                    :status="getScoreStatus(task.avgScore)"
                    :stroke-width="6"
                  />
                </div>
              </div>

              <div class="task-description">
                {{ task.description }}
              </div>

              <div class="task-actions">
                <el-button size="small" @click="viewTaskDetail(task)"> 查看详情 </el-button>
                <el-button size="small" type="primary" @click="viewAnalysis(task)">
                  数据分析
                </el-button>
                <el-dropdown>
                  <el-button size="small">
                    更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="duplicateTask(task)">复制任务</el-dropdown-item>
                      <el-dropdown-item
                        v-if="task.status !== 'archived'"
                        @click="archiveTask(task)"
                      >
                        归档
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="task.status === 'archived'"
                        @click="restoreTask(task)"
                      >
                        恢复
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="exportTaskData(task)">
                        导出数据
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div class="pagination" v-if="filteredTasks.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalTasks"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 任务详情抽屉 -->
    <el-drawer v-model="taskDetailDrawer" :title="selectedTask?.title" direction="rtl" size="60%">
      <div v-if="selectedTask" class="task-detail">
        <div class="task-detail-header">
          <div class="detail-status">
            <el-tag :type="getStatusTagType(selectedTask.status)">
              {{ getStatusText(selectedTask.status) }}
            </el-tag>
          </div>
          <div class="detail-dates">
            <div class="date-item">
              <span class="date-label">创建时间:</span>
              <span>{{ selectedTask.createTime }}</span>
            </div>
            <div class="date-item" v-if="selectedTask.completionTime">
              <span class="date-label">完成时间:</span>
              <span>{{ selectedTask.completionTime }}</span>
            </div>
          </div>
        </div>

        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="任务ID">{{ selectedTask.id }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ selectedTask.course }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ selectedTask.class }}</el-descriptions-item>
          <el-descriptions-item label="学生数量"
            >{{ selectedTask.studentsCount }}人</el-descriptions-item
          >
          <el-descriptions-item label="完成率"
            >{{ selectedTask.progressRate }}%</el-descriptions-item
          >
          <el-descriptions-item label="平均分数">{{ selectedTask.avgScore }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">任务描述</el-divider>
        <div class="detail-description">
          {{ selectedTask.description }}
        </div>

        <el-divider content-position="left">资源与习题</el-divider>
        <el-collapse>
          <el-collapse-item title="教学资源" name="resources">
            <el-table :data="selectedTask.resources" style="width: 100%">
              <el-table-column prop="name" label="资源名称" />
              <el-table-column prop="type" label="类型">
                <template #default="scope">
                  <el-tag size="small" :type="getResourceTypeTag(scope.row.type)">
                    {{ getResourceTypeName(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="size" label="大小">
                <template #default="scope">
                  {{ formatFileSize(scope.row.size) }}
                </template>
              </el-table-column>
              <el-table-column prop="viewCount" label="查看次数" />
              <el-table-column prop="downloadCount" label="下载次数" />
            </el-table>
          </el-collapse-item>

          <el-collapse-item title="习题统计" name="exercises">
            <div class="exercise-stats">
              <div class="exercise-chart" id="exercise-chart"></div>
              <div class="exercise-summary">
                <div class="summary-item">
                  <div class="summary-value">{{ selectedTask.exercises.total }}</div>
                  <div class="summary-label">总题目数</div>
                </div>
                <div class="summary-item">
                  <div class="summary-value">{{ selectedTask.exercises.submitted }}</div>
                  <div class="summary-label">已提交数</div>
                </div>
                <div class="summary-item">
                  <div class="summary-value">{{ selectedTask.exercises.correctRate }}%</div>
                  <div class="summary-label">正确率</div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>

        <el-divider content-position="left">学生完成情况</el-divider>
        <el-table
          :data="selectedTask.studentRecords"
          style="width: 100%"
          :default-sort="{ prop: 'score', order: 'descending' }"
        >
          <el-table-column prop="name" label="学生姓名" sortable />
          <el-table-column prop="studentId" label="学号" width="120" />
          <el-table-column prop="completion" label="完成度" width="180" sortable>
            <template #default="scope">
              <el-progress
                :percentage="scope.row.completion"
                :status="getProgressStatus(scope.row.completion)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="score" label="得分" width="100" sortable />
          <el-table-column prop="submitTime" label="提交时间" width="180" sortable />
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const router = useRouter()

// 定义任务类型
interface Task {
  id: string
  title: string
  description: string
  status: string
  course: string
  class: string
  createTime: string
  completionTime: string
  studentsCount: number
  progressRate: number
  avgScore: number
  resources: any[]
  exercises: {
    total: number
    submitted: number
    correctRate: number
    typeDistribution: { name: string; value: number }[]
  }
  studentRecords: any[]
}

// 列表过滤与分页
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const dateRange = ref<string[] | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalTasks = ref(0)

// 任务详情
const taskDetailDrawer = ref(false)
const selectedTask = ref<Task | null>(null)
let exerciseChart: echarts.ECharts | null = null

// 模拟数据
const tasks = ref([
  {
    id: '1001',
    title: '面向对象程序设计基础',
    description:
      '本任务旨在帮助学生掌握面向对象编程的基本概念和原则，通过实践练习培养学生的面向对象思维和编程能力。',
    status: 'completed',
    course: '程序设计基础',
    class: '高二(1)班',
    createTime: '2023-10-15',
    completionTime: '2023-11-15',
    studentsCount: 42,
    progressRate: 95,
    avgScore: 87,
    resources: [
      {
        name: '面向对象编程课件.pptx',
        type: 'document',
        size: 5 * 1024 * 1024,
        viewCount: 38,
        downloadCount: 25,
      },
      {
        name: '类与对象示例.mp4',
        type: 'video',
        size: 65 * 1024 * 1024,
        viewCount: 42,
        downloadCount: 15,
      },
      {
        name: '继承与多态练习.pdf',
        type: 'document',
        size: 2 * 1024 * 1024,
        viewCount: 40,
        downloadCount: 35,
      },
    ],
    exercises: {
      total: 25,
      submitted: 24,
      correctRate: 82,
      typeDistribution: [
        { name: '选择题', value: 10 },
        { name: '填空题', value: 5 },
        { name: '问答题', value: 5 },
        { name: '编程题', value: 5 },
      ],
    },
    studentRecords: [
      {
        name: '张三',
        studentId: '20230001',
        completion: 100,
        score: 92,
        submitTime: '2023-11-14 14:23:45',
      },
      {
        name: '李四',
        studentId: '20230002',
        completion: 92,
        score: 85,
        submitTime: '2023-11-15 09:12:30',
      },
      {
        name: '王五',
        studentId: '20230003',
        completion: 100,
        score: 88,
        submitTime: '2023-11-14 16:40:22',
      },
      {
        name: '赵六',
        studentId: '20230004',
        completion: 88,
        score: 78,
        submitTime: '2023-11-15 11:30:15',
      },
      {
        name: '钱七',
        studentId: '20230005',
        completion: 96,
        score: 90,
        submitTime: '2023-11-14 15:18:50',
      },
    ],
  },
  {
    id: '1002',
    title: '数据结构与算法入门',
    description:
      '介绍基本数据结构和算法的概念、原理和应用，包括数组、链表、栈、队列、树、图等数据结构以及排序、搜索等常见算法。',
    status: 'active',
    course: '数据结构基础',
    class: '高二(2)班',
    createTime: '2023-11-01',
    completionTime: '',
    studentsCount: 38,
    progressRate: 65,
    avgScore: 75,
    resources: [
      {
        name: '数据结构概述.pptx',
        type: 'document',
        size: 4 * 1024 * 1024,
        viewCount: 35,
        downloadCount: 20,
      },
      {
        name: '链表操作演示.mp4',
        type: 'video',
        size: 55 * 1024 * 1024,
        viewCount: 30,
        downloadCount: 12,
      },
      {
        name: '排序算法比较.pdf',
        type: 'document',
        size: 3 * 1024 * 1024,
        viewCount: 28,
        downloadCount: 15,
      },
    ],
    exercises: {
      total: 20,
      submitted: 15,
      correctRate: 72,
      typeDistribution: [
        { name: '选择题', value: 8 },
        { name: '填空题', value: 4 },
        { name: '问答题', value: 3 },
        { name: '编程题', value: 5 },
      ],
    },
    studentRecords: [
      {
        name: '张三',
        studentId: '20230001',
        completion: 80,
        score: 82,
        submitTime: '2023-11-20 10:15:30',
      },
      {
        name: '李四',
        studentId: '20230002',
        completion: 60,
        score: 70,
        submitTime: '2023-11-19 16:45:22',
      },
      {
        name: '王五',
        studentId: '20230003',
        completion: 75,
        score: 78,
        submitTime: '2023-11-21 09:30:45',
      },
      {
        name: '赵六',
        studentId: '20230004',
        completion: 50,
        score: 65,
        submitTime: '2023-11-18 14:20:18',
      },
      {
        name: '钱七',
        studentId: '20230005',
        completion: 70,
        score: 75,
        submitTime: '2023-11-20 11:10:40',
      },
    ],
  },
  {
    id: '1003',
    title: 'Web前端开发基础',
    description:
      'HTML、CSS和JavaScript基础教学，帮助学生了解网页构建的核心技术和前端开发的基本流程。',
    status: 'archived',
    course: 'Web开发入门',
    class: '高二(3)班',
    createTime: '2023-09-10',
    completionTime: '2023-10-10',
    studentsCount: 40,
    progressRate: 90,
    avgScore: 82,
    resources: [
      {
        name: 'HTML5基础教程.pdf',
        type: 'document',
        size: 6 * 1024 * 1024,
        viewCount: 38,
        downloadCount: 32,
      },
      {
        name: 'CSS样式讲解.mp4',
        type: 'video',
        size: 70 * 1024 * 1024,
        viewCount: 36,
        downloadCount: 20,
      },
      {
        name: 'JavaScript入门示例.zip',
        type: 'other',
        size: 10 * 1024 * 1024,
        viewCount: 35,
        downloadCount: 30,
      },
    ],
    exercises: {
      total: 30,
      submitted: 28,
      correctRate: 78,
      typeDistribution: [
        { name: '选择题', value: 12 },
        { name: '填空题', value: 8 },
        { name: '问答题', value: 5 },
        { name: '编程题', value: 5 },
      ],
    },
    studentRecords: [
      {
        name: '张三',
        studentId: '20230001',
        completion: 95,
        score: 88,
        submitTime: '2023-10-08 15:20:45',
      },
      {
        name: '李四',
        studentId: '20230002',
        completion: 100,
        score: 90,
        submitTime: '2023-10-07 14:35:30',
      },
      {
        name: '王五',
        studentId: '20230003',
        completion: 85,
        score: 78,
        submitTime: '2023-10-09 09:45:22',
      },
      {
        name: '赵六',
        studentId: '20230004',
        completion: 90,
        score: 82,
        submitTime: '2023-10-08 16:15:18',
      },
      {
        name: '钱七',
        studentId: '20230005',
        completion: 100,
        score: 86,
        submitTime: '2023-10-07 10:50:40',
      },
    ],
  },
])

// 计算属性: 过滤后的任务列表
const filteredTasks = computed(() => {
  let result = tasks.value.slice()

  // 按关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      (task) =>
        task.title.toLowerCase().includes(query) || task.description.toLowerCase().includes(query),
    )
  }

  // 按状态过滤
  if (statusFilter.value) {
    result = result.filter((task) => task.status === statusFilter.value)
  }

  // 按日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])

    result = result.filter((task) => {
      const taskDate = new Date(task.createTime)
      return taskDate >= startDate && taskDate <= endDate
    })
  }

  // 分页处理
  totalTasks.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  return result.slice(start, end)
})

// 初始化
onMounted(() => {
  loading.value = true

  // 模拟API请求延迟
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 方法
const applyFilters = () => {
  currentPage.value = 1
  // 实际项目中这里会调用API获取数据
  loading.value = true

  setTimeout(() => {
    loading.value = false
    ElMessage.success('筛选条件已应用')
  }, 500)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  // 实际项目中这里会调用API获取数据
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  // 实际项目中这里会调用API获取数据
}

const viewTaskDetail = (task: Task) => {
  selectedTask.value = task
  taskDetailDrawer.value = true

  // 初始化习题图表
  nextTick(() => {
    if (exerciseChart) {
      exerciseChart.dispose()
    }

    const chartDom = document.getElementById('exercise-chart')
    if (chartDom) {
      exerciseChart = echarts.init(chartDom)

      exerciseChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'center',
          data: task.exercises.typeDistribution.map(
            (item: { name: string; value: number }) => item.name,
          ),
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: task.exercises.typeDistribution,
          },
        ],
      })
    }
  })
}

const viewAnalysis = (task: Task) => {
  router.push(`/analysis/${task.id}`)
}

const duplicateTask = (task: Task) => {
  ElMessageBox.confirm(`确定要复制任务 "${task.title}" 吗？`, '复制确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(() => {
      // 实际项目中这里调用API复制任务
      ElMessage.success('任务已复制，请在任务列表中查看')
    })
    .catch(() => {})
}

const archiveTask = (task: Task) => {
  ElMessageBox.confirm(`确定要归档任务 "${task.title}" 吗？`, '归档确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 实际项目中这里调用API归档任务
      const index = tasks.value.findIndex((t) => t.id === task.id)
      if (index !== -1) {
        tasks.value[index] = { ...tasks.value[index], status: 'archived' }
        if (selectedTask.value && selectedTask.value.id === task.id) {
          selectedTask.value = { ...selectedTask.value, status: 'archived' }
        }
      }
      ElMessage.success('任务已归档')
    })
    .catch(() => {})
}

const restoreTask = (task: Task) => {
  // 实际项目中这里调用API恢复任务
  const index = tasks.value.findIndex((t) => t.id === task.id)
  if (index !== -1) {
    tasks.value[index] = { ...tasks.value[index], status: 'completed' }
    if (selectedTask.value && selectedTask.value.id === task.id) {
      selectedTask.value = { ...selectedTask.value, status: 'completed' }
    }
  }
  ElMessage.success('任务已恢复')
}

const exportTaskData = (task: Task) => {
  ElMessage.success(`正在导出任务 "${task.title}" 的数据，请稍候...`)
  // 实际项目中这里处理导出逻辑
}

// 工具函数
const getTimelineItemType = (status: string) => {
  if (status === 'active') return 'primary'
  if (status === 'completed') return 'success'
  return 'info'
}

const getTimelineItemColor = (status: string) => {
  if (status === 'active') return '#409EFF'
  if (status === 'completed') return '#67C23A'
  return '#909399'
}

const getStatusTagType = (status: string) => {
  if (status === 'active') return 'primary'
  if (status === 'completed') return 'success'
  return 'info'
}

const getStatusText = (status: string) => {
  if (status === 'active') return '进行中'
  if (status === 'completed') return '已完成'
  return '已归档'
}

const getProgressStatus = (value: number) => {
  if (value < 60) return 'exception'
  if (value < 80) return 'warning'
  return 'success'
}

const getScoreStatus = (value: number) => {
  if (value < 60) return 'exception'
  if (value < 80) return 'warning'
  return 'success'
}

const getResourceTypeTag = (type: string) => {
  if (type === 'document') return 'success'
  if (type === 'video') return 'primary'
  if (type === 'image') return 'warning'
  return 'info'
}

const getResourceTypeName = (type: string) => {
  if (type === 'document') return '文档'
  if (type === 'video') return '视频'
  if (type === 'image') return '图片'
  return '其他'
}

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) {
    return bytes + ' B'
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(1) + ' KB'
  } else {
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  }
}
</script>

<style scoped>
.history-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 24px;
  color: #333;
}

.filters {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.filter-select {
  width: 120px;
}

.date-range {
  width: 350px;
}

.task-list {
  min-height: 200px;
}

.empty-state {
  padding: 40px 0;
}

.task-card {
  margin-bottom: 10px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-title {
  margin: 0;
  font-size: 18px;
}

.task-content {
  margin-top: 10px;
}

.task-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  color: #909399;
  margin-right: 5px;
}

.task-stats {
  display: flex;
  gap: 30px;
  margin-bottom: 15px;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.task-description {
  margin-bottom: 15px;
  color: #606266;
  line-height: 1.6;
}

.task-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 任务详情样式 */
.task-detail {
  padding: 15px;
}

.task-detail-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.detail-dates {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.date-item {
  display: flex;
  align-items: center;
}

.date-label {
  color: #909399;
  margin-right: 5px;
}

.detail-description {
  margin-bottom: 20px;
  line-height: 1.6;
  color: #606266;
}

.exercise-stats {
  display: flex;
  flex-wrap: wrap;
}

.exercise-chart {
  height: 300px;
  width: 60%;
}

.exercise-summary {
  width: 40%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20px;
}

.summary-item {
  text-align: center;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.summary-label {
  font-size: 14px;
  color: #909399;
}
</style>
